<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\model;

class Posts extends ApiBase
{
    public function getShortLinkAttr($value)
    {
        if ($value === null) {
            return '';
        }

        return $value;
    }

    public function getThumbAttr($value, $data)
    {
        if ($value && !preg_match('/^http(s)?:\\/\\/.+/', $value)) {
            return SITE_PATH . $value;
        } else {
            return $value;
        }
    }

    public function getDatetimeAttr($value)
    {
        if ($value) {
            return date('Y-m-d H:i', $value);
        } else {
            return $value;
        }
    }

    public function getUpdatetimeAttr($value)
    {
        if ($value) {
            return date('Y-m-d H:i', $value);
        } else {
            return $value;
        }
    }

    /**
     * 处理html内容中的图片链接等
     * @param  string $value content
     * @param  array $data   原始数据
     * @return string
     */
    public function getContentAttr($content, $data)
    {
        $content = preg_replace('#<!--[^\!\[]*?(?<!\/\/)-->#','', $content);
        preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $content, $match);
        foreach ($match[1] as $key => $url) {
            if ($url && !preg_match('/^http(s)?:\\/\\/.+/', $url)) {
                $content = str_replace($url, SITE_PATH . $url, $content);
            }
        }

        return $content;
    }

    public function postsImages(){
        return $this->hasMany('PostsImages','posts_id','id');
    }

    public function postsVideos(){
        return $this->hasMany('PostsVideos','posts_id','id');
    }
}